import { HTTP } from '../utils/http.js'

class ClassicModel extends HTTP {
  getLatest (callback) {
    this.request({
      url: '/classic/latest',
      success: (res) => {
        this._setLatestIndex(res.index)
        wx.setStorageSync(this._getKey(res.index), res)
        callback(res)
      }
    })
  }

  /**
   * direction有两个值，previous和next
   */
  getClassic (index, direction, callback) {
    const curIndex = direction === 'next' ? index + 1 : index - 1
    const key = this._getKey(curIndex)
    const classic = wx.getStorageSync(key)

    if (!classic) {
      this.request({
        url: `/classic/${index}/${direction}`,
        success: (res) => {
          wx.setStorageSync(this._getKey(res.index), res)
          callback(res)
        }
      })
    } else {
      callback(classic)
    }
    
  }

  getIsFirst (index) {
    return index === 1
  }

  getIsLatest (index) {
    return index === this._getLatestIndex()
  }

  getMyFavor (callback) {
    this.request({
      url: '/classic/favor',
      success: callback
    })
  }

  getById (cid, type, callback) {
    this.request({
      url: `/classic/${type}/${cid}`,
      success: callback
    })
  }

  /**
   * _打头的方法表示私有方法
   * 不暴露给外部使用，仅用于内部使用
   */
  _setLatestIndex (index) {
    wx.setStorageSync('latestIndex', index)
  }

  _getLatestIndex () {
    return wx.getStorageSync('latestIndex')
  }

  _getKey (index) {
    return `classic-${index}`
  }
}

export { ClassicModel }